import {
  View,
  Text,
  Image,
  Video,
  ScrollView,
  Swiper,
  SwiperItem,
  Canvas,
} from "@tarojs/components";
import { useState, useRef, useEffect } from "react";
import Taro from "@tarojs/taro";
import "./index.scss";

interface PreviewModalProps {
  visible: boolean;
  type: "text" | "image" | "video" | "carousel";
  data: any;
  onClose: () => void;
}

const ICONS = {
  close: "https://api.iconify.design/material-symbols:close-rounded.svg",
  edit: "https://api.iconify.design/material-symbols:edit.svg",
  magic:
    "https://api.iconify.design/material-symbols:auto-fix-high-rounded.svg",
  zoom: "https://api.iconify.design/material-symbols:zoom-in-rounded.svg",
  crop: "https://api.iconify.design/material-symbols:crop-rounded.svg",
  watermark:
    "https://api.iconify.design/material-symbols:water-drop-rounded.svg",
  cut: "https://api.iconify.design/material-symbols:content-cut-rounded.svg",
  frame: "https://api.iconify.design/material-symbols:animation.svg",
};

export default function PreviewModal({
  visible,
  type,
  data,
  onClose,
}: PreviewModalProps) {
  const [textContent, setTextContent] = useState(data?.text || "");
  const [editedText, setEditedText] = useState(data?.text || "");
  const [isExtractingFrames, setIsExtractingFrames] = useState(false);
  const [extractedFrames, setExtractedFrames] = useState<string[]>([]);
  const [extractionProgress, setExtractionProgress] = useState(0);
  const [showFramesModal, setShowFramesModal] = useState(false);
  const videoRef = useRef<any>(null);
  const canvasRef = useRef<any>(null);

  if (!visible) return null;

  const handleTextOperation = (operation: string) => {
    // 这里应该调用AI API进行文本处理
    switch (operation) {
      case "polish":
        // 文本润色
        setEditedText(`[润色后的文本] ${textContent}`);
        break;
      case "rewrite":
        // AI风格改写
        setEditedText(`[AI改写后的文本] ${textContent}`);
        break;
      default:
        break;
    }
  };

  const extractVideoFrames = async () => {
    if (!videoRef.current) return;

    setIsExtractingFrames(true);
    setExtractionProgress(0);
    setExtractedFrames([]);

    try {
      const video = videoRef.current;

      // 在Taro环境中使用createCanvasContext
      const ctx = Taro.createCanvasContext('videoFrameCanvas');

      const frames: string[] = [];
      const frameRate = 10; // 每秒提取10帧
      const duration = video.duration;
      const totalFrames = Math.floor(duration * frameRate);

      for (let i = 0; i < totalFrames; i++) {
        const time = i / frameRate;
        video.currentTime = time;

        // 等待视频跳转到指定时间
        await new Promise(resolve => {
          video.addEventListener('seeked', resolve, { once: true });
        });

        // 在Taro环境中绘制视频帧到canvas
        ctx.drawImage(video.src, 0, 0, 300, 200);
        ctx.draw(false, () => {
          // 绘制完成后获取临时文件路径
          Taro.canvasToTempFilePath({
            canvasId: 'videoFrameCanvas',
            fileType: 'jpg',
            quality: 0.8,
            success: (res) => {
              frames.push(res.tempFilePath);
              if (frames.length === totalFrames) {
                setExtractedFrames(frames);
                setShowFramesModal(true);
              }
            },
            fail: (error) => {
              console.error('Canvas转图片失败:', error);
            }
          });
        });

        // 更新进度
        setExtractionProgress(Math.floor((i + 1) / totalFrames * 100));

        // 添加延迟避免过快操作
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    } catch (error) {
      console.error('提取视频帧失败:', error);
      Taro.showToast({
        title: '提取失败',
        icon: 'error'
      });
    } finally {
      setIsExtractingFrames(false);
    }
  };

  const downloadFrame = (frameData: string, index: number) => {
    // 在Taro环境中使用saveImageToPhotosAlbum保存图片
    Taro.saveImageToPhotosAlbum({
      filePath: frameData,
      success: () => {
        Taro.showToast({
          title: `已保存帧 ${index + 1}`,
          icon: 'success'
        });
      },
      fail: (error) => {
        console.error('保存图片失败:', error);
        Taro.showToast({
          title: '保存失败',
          icon: 'error'
        });
      }
    });
  };

  const downloadAllFrames = async () => {
    for (let i = 0; i < extractedFrames.length; i++) {
      await new Promise(resolve => {
        Taro.saveImageToPhotosAlbum({
          filePath: extractedFrames[i],
          success: () => {
            Taro.showToast({
              title: `已保存帧 ${i + 1}`,
              icon: 'success'
            });
          },
          fail: (error) => {
            console.error('保存图片失败:', error);
            Taro.showToast({
              title: '保存失败',
              icon: 'error'
            });
          },
          complete: resolve
        });
      });

      // 添加延迟避免过快操作
      await new Promise(resolve => setTimeout(resolve, 200));
    }

    Taro.showToast({
      title: '全部保存完成',
      icon: 'success'
    });
  };

  const renderTextPreview = () => (
    <View className="bg-white flex flex-col h-full max-h-85vh rounded-2xl shadow-2xl">
      <View className="flex justify-between items-center p-20px bg-gradient-to-r from-indigo-600 to-purple-700 text-white rounded-t-2xl">
        <Text className="text-20px font-bold">文本预览</Text>
        <Image className="w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity" src={ICONS.close} onClick={onClose} />
      </View>

      <ScrollView className="flex-1 p-25px overflow-y-auto text-16px leading-1.6 whitespace-pre-wrap bg-gray-50">
        <Text className="text-gray-800">{editedText || textContent}</Text>
      </ScrollView>

      <View className="p-20px border-t-1px border-t-gray-200 bg-white rounded-b-2xl">
        <View className="flex justify-around gap-15px">
          <View
            className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-blue-50 to-indigo-50 hover:from-blue-100 hover:to-indigo-100 transition-all-300ms active:scale-95 cursor-pointer border border-blue-100"
            onClick={() => handleTextOperation("polish")}
          >
            <Image className="w-8 h-8 mb-8px" src={ICONS.edit} />
            <Text className="text-14px text-gray-700 font-medium">内容润色</Text>
          </View>
          <View
            className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-purple-50 to-pink-50 hover:from-purple-100 hover:to-pink-100 transition-all-300ms active:scale-95 cursor-pointer border border-purple-100"
            onClick={() => handleTextOperation("rewrite")}
          >
            <Image className="w-8 h-8 mb-8px" src={ICONS.magic} />
            <Text className="text-14px text-gray-700 font-medium">AI改写</Text>
          </View>
        </View>
      </View>
    </View>
  );

  const renderImagePreview = () => (
    <View className="bg-white flex flex-col h-full max-h-85vh rounded-2xl shadow-2xl">
      <View className="flex justify-between items-center p-20px bg-gradient-to-r from-indigo-600 to-purple-700 text-white rounded-t-2xl">
        <Text className="text-20px font-bold">图片预览</Text>
        <Image className="w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity" src={ICONS.close} onClick={onClose} />
      </View>

      <View className="flex-1 flex items-center justify-center p-25px bg-gray-50">
        <Image
          className="max-w-full max-h-65vh rounded-16px shadow-lg"
          src={data?.url}
          mode="aspectFit"
        />
      </View>

      <View className="p-20px border-t-1px border-t-gray-200 bg-white rounded-b-2xl">
        <View className="flex justify-around gap-10px">
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-green-50 to-emerald-50 hover:from-green-100 hover:to-emerald-100 transition-all-300ms active:scale-95 cursor-pointer border border-green-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.zoom} />
            <Text className="text-14px text-gray-700 font-medium">无损放大</Text>
          </View>
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-yellow-50 to-orange-50 hover:from-yellow-100 hover:to-orange-100 transition-all-300ms active:scale-95 cursor-pointer border border-yellow-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.crop} />
            <Text className="text-14px text-gray-700 font-medium">区域截图</Text>
          </View>
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-red-50 to-pink-50 hover:from-red-100 hover:to-pink-100 transition-all-300ms active:scale-95 cursor-pointer border border-red-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.watermark} />
            <Text className="text-14px text-gray-700 font-medium">去水印</Text>
          </View>
        </View>
      </View>
    </View>
  );

  const renderVideoPreview = () => (
    <View className="bg-white flex flex-col h-full max-h-85vh rounded-2xl shadow-2xl">
      <View className="flex justify-between items-center p-20px bg-gradient-to-r from-indigo-600 to-purple-700 text-white rounded-t-2xl">
        <Text className="text-20px font-bold">视频预览</Text>
        <Image className="w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity" src={ICONS.close} onClick={onClose} />
      </View>

      <View className="flex-1 flex items-center justify-center p-25px bg-gray-50">
        <Video
          ref={videoRef}
          className="w-full max-h-65vh rounded-16px shadow-lg"
          src={data?.url}
          controls
          autoplay
        />
      </View>

      <View className="p-20px border-t-1px border-t-gray-200 bg-white rounded-b-2xl">
        <View className="flex justify-around gap-10px">
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-cyan-50 to-blue-50 hover:from-cyan-100 hover:to-blue-100 transition-all-300ms active:scale-95 cursor-pointer border border-cyan-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.watermark} />
            <Text className="text-14px text-gray-700 font-medium">去水印</Text>
          </View>
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-purple-50 to-violet-50 hover:from-purple-100 hover:to-violet-100 transition-all-300ms active:scale-95 cursor-pointer border border-purple-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.cut} />
            <Text className="text-14px text-gray-700 font-medium">片段提取</Text>
          </View>
          <View
            className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-teal-50 to-green-50 hover:from-teal-100 hover:to-green-100 transition-all-300ms active:scale-95 cursor-pointer border border-teal-100"
            onClick={extractVideoFrames}
          >
            <Image className="w-8 h-8 mb-8px" src={ICONS.frame} />
            <Text className="text-14px text-gray-700 font-medium">逐帧转图</Text>
          </View>
        </View>
      </View>
    </View>
  );

  const renderCarouselPreview = () => (
    <View className="bg-white flex flex-col h-full max-h-85vh rounded-2xl shadow-2xl">
      <View className="flex justify-between items-center p-20px bg-gradient-to-r from-indigo-600 to-purple-700 text-white rounded-t-2xl">
        <Text className="text-20px font-bold">图片预览</Text>
        <Image className="w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity" src={ICONS.close} onClick={onClose} />
      </View>

      <Swiper className="flex-1 h-65vh bg-gray-50" indicatorDots autoplay circular>
        {data?.images?.map((img: string, index: number) => (
          <SwiperItem key={index}>
            <View className="flex items-center justify-center p-25px">
              <Image className="w-full max-h-65vh rounded-16px shadow-lg" src={img} mode="aspectFit" />
            </View>
          </SwiperItem>
        ))}
      </Swiper>

      <View className="p-20px border-t-1px border-t-gray-200 bg-white rounded-b-2xl">
        <View className="flex justify-around gap-10px">
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-green-50 to-emerald-50 hover:from-green-100 hover:to-emerald-100 transition-all-300ms active:scale-95 cursor-pointer border border-green-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.zoom} />
            <Text className="text-14px text-gray-700 font-medium">无损放大</Text>
          </View>
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-yellow-50 to-orange-50 hover:from-yellow-100 hover:to-orange-100 transition-all-300ms active:scale-95 cursor-pointer border border-yellow-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.crop} />
            <Text className="text-14px text-gray-700 font-medium">区域截图</Text>
          </View>
          <View className="flex flex-col items-center p-15px rounded-12px bg-gradient-to-br from-red-50 to-pink-50 hover:from-red-100 hover:to-pink-100 transition-all-300ms active:scale-95 cursor-pointer border border-red-100">
            <Image className="w-8 h-8 mb-8px" src={ICONS.watermark} />
            <Text className="text-14px text-gray-700 font-medium">去水印</Text>
          </View>
        </View>
      </View>
    </View>
  );

  const renderFramesModal = () => {
    if (!showFramesModal) return null;

    return (
      <View
        className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-80 flex items-center justify-center z-9999 backdrop-blur-8px p-10px"
        onClick={() => setShowFramesModal(false)}
      >
        <View
          className="w-full max-w-6xl max-h-full bg-white rounded-2xl shadow-2xl overflow-hidden"
          onClick={(e) => e.stopPropagation()}
        >
          <View className="flex justify-between items-center p-20px bg-gradient-to-r from-teal-600 to-green-600 text-white">
            <Text className="text-20px font-bold">提取的视频帧 ({extractedFrames.length} 帧)</Text>
            <Image className="w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity" src={ICONS.close} onClick={() => setShowFramesModal(false)} />
          </View>

          <View className="p-20px">
            <View className="flex justify-between items-center mb-20px">
              <Text className="text-16px text-gray-700">点击图片下载单帧，或使用批量下载</Text>
              <View className="flex gap-10px">
                <View
                  className="px-15px py-8px bg-teal-500 text-white rounded-8px cursor-pointer hover:bg-teal-600 transition-colors"
                  onClick={downloadAllFrames}
                >
                  <Text className="text-14px">批量下载</Text>
                </View>
              </View>
            </View>

            <ScrollView className="max-h-70vh overflow-y-auto">
              <View className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-15px">
                {extractedFrames.map((frame, index) => (
                  <View key={index} className="flex flex-col items-center">
                    <Image
                      className="w-full h-120px object-cover rounded-8px border-2px border-gray-200 cursor-pointer hover:border-teal-400 transition-colors"
                      src={frame}
                      onClick={() => downloadFrame(frame, index)}
                    />
                    <Text className="text-12px text-gray-600 mt-5px">帧 {index + 1}</Text>
                  </View>
                ))}
              </View>
            </ScrollView>
          </View>
        </View>
      </View>
    );
  };

  const renderContent = () => {
    switch (type) {
      case "text":
        return renderTextPreview();
      case "image":
        return renderImagePreview();
      case "video":
        return renderVideoPreview();
      case "carousel":
        return renderCarouselPreview();
      default:
        return null;
    }
  };

  return (
    <>
      <View
        className="fixed top-0 z-20 left-0 w-full h-full bg-black bg-opacity-80 flex items-center justify-center z-9999 backdrop-blur-8px p-10px"
        onClick={onClose}
      >
        <View
          className="w-full max-w-4xl max-h-full rounded-2xl overflow-hidden animate-pop shadow-2xl"
          onClick={(e) => e.stopPropagation()}
        >
          {renderContent()}
        </View>
      </View>

      {renderFramesModal()}

      {/* 隐藏的Canvas用于视频帧提取 */}
      <Canvas
        canvasId="videoFrameCanvas"
        className="hidden"
        style={{ display: 'none', width: '300px', height: '200px' }}
      />

      {/* 提取进度提示 */}
      {isExtractingFrames && (
        <View className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-80 flex items-center justify-center z-30">
          <View className="bg-white p-30px rounded-16px shadow-2xl">
            <Text className="text-18px font-bold mb-15px">正在提取视频帧...</Text>
            <Text className="text-16px text-gray-600 mb-20px">进度: {extractionProgress}%</Text>
            <View className="w-200px h-4px bg-gray-200 rounded-full overflow-hidden">
              <View
                className="h-full bg-gradient-to-r from-teal-500 to-green-500 transition-all-300ms"
                style={{ width: `${extractionProgress}%` }}
              />
            </View>
          </View>
        </View>
      )}
    </>
  );
}
